import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {ActionSheetController, Events, LoadingController, NavController, Platform, ToastController} from '@ionic/angular';
import {Camera, CameraOptions} from '@ionic-native/camera/ngx';
import {FileTransfer, FileUploadOptions, FileTransferObject} from '@ionic-native/file-transfer/ngx';
import {File} from '@ionic-native/file/ngx';
import {FilePath} from '@ionic-native/file-path/ngx';
import {WebView} from '@ionic-native/ionic-webview/ngx';
import {AppConfig} from '../../common/app-config.enum';
import {Storage} from '@ionic/storage';
import {BasePage} from '../../common/basePage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';

@Component({
  selector: 'app-user-avatar',
  templateUrl: './user-avatar.page.html',
  styleUrls: ['./user-avatar.page.scss'],
})
export class UserAvatarPage extends BasePage implements OnInit {

  public userInfo: any;
  public avatar = ''; // 头像路径
  public lastFilePath = null; // 最终文件路径(显示用)
  public uploadFilePath = null; // 最终文件路径(上传用)
  public fileName: string; // 文件名
  public fileSuffix = '.jpg'; // 默认文件后缀
  private cameraOptions: CameraOptions = {
    destinationType: this.camera.DestinationType.FILE_URI,
    quality: 100,
    saveToPhotoAlbum: false, // 拍照后是否保存到相册
    correctOrientation: true, // 是否纠正拍摄的照片方向
    targetWidth: 240,
    targetHeight: 240,
    allowEdit: true
  };

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private activatedRoute: ActivatedRoute,
              private actionSheetCtrl: ActionSheetController,
              private loadingCtrl: LoadingController,
              private storage: Storage,
              private events: Events,
              private platform: Platform,
              private webView: WebView,
              private camera: Camera,
              private file: File,
              private filePath: FilePath,
              private fileTransfer: FileTransfer
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.avatar = this.activatedRoute.snapshot.params['photo'];
    this.lastFilePath = this.avatar;
    this.getUserInfo();
  }

  // 获取用户信息
  private async getUserInfo() {
    this.userInfo = await this.storage.get(AppConfig.USER_INFO);
  }

  async presentActionSheet() {
    const actionSheet = await this.actionSheetCtrl.create({
      buttons: [
        {
          text: '相册选择',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        }, {
          text: '拍摄照片',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        }, {
          text: '取消',
          role: 'cancel'
        }
      ]
    });
    await actionSheet.present();
  }

  private async takePicture(sourceType: number) {
    try {
      this.cameraOptions.sourceType = sourceType;
      const imagePath = await this.camera.getPicture(this.cameraOptions);
      this.lastFilePath = null;
      let path = '';
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) { // 来源android相册
        path = await this.filePath.resolveNativePath(imagePath);
      } else { // 其它来源
        path = imagePath;
      }
      this.lastFilePath = this.convertPath(path);
      this.uploadFilePath = path;
      this.fileName = path.substr(path.lastIndexOf('/') + 1); // 获取文件名
      this.fileSuffix = this.fileName.substring(this.fileName.lastIndexOf('.')); // 获取后缀名
    } catch (e) {
      // 未选择或选择出错关闭页面
      this.goBack();
    }
  }

  // 执行上传
  async uploadImage() {
    const loading = await this.loadingCtrl.create({
      message: '上传中'
    });
    await loading.present();
    try {
      // 上传的参数 File imgFile, String fileName, String userId
      const fileUploadOptions = {
        fileKey: 'imgFile',
        fileName: this.fileName,
        chunkedMode: false,
        mimeType: 'multipart/form-data',
        params: {'userId': this.userInfo['userId'], 'fileName': this.fileName}
      } as FileUploadOptions;
      // 创建传输对象
      const fileTransferObject: FileTransferObject = this.fileTransfer.create();
      // 开始上传
      const uploadPromise$ = fileTransferObject.upload(this.uploadFilePath, this.HOST + UrlAndOPT.USER_AVATAR, fileUploadOptions);
      // 加入超时机制
      const fileUploadResult = await this.setTimeOverPromise(uploadPromise$);
      const response = JSON.parse(fileUploadResult.response);
      await loading.dismiss();
      if (response['code'] > 0) {
        // 发送头像变更通知
        this.events.publish(AppConfig.TOPIC_USER_AVATAR, response['obj']);
        await this.showToast('上传成功');
      } else {
        await this.showToast('上传失败');
      }
    } catch (e) {
      await loading.dismiss();
      await this.showToast('文件发送失败，请重新上传');
    }
    this.goBack();
  }

  // 设置上传超时机制
  async setTimeOverPromise(promise$: Promise<any>): Promise<any> {
    const timeout$ = new Promise<number>((resolve, reject) => setTimeout(() => reject('timeout'), 10000));
    return await Promise.race([timeout$, promise$]);
  }

  // 去除路径的file://前缀，转为页面可读取的路径
  private convertPath(filePath: string): string {
    if (filePath) {
      return this.webView.convertFileSrc(filePath) + '?timestamp=' + new Date().getTime();
    }
    return '';
  }

}
